package com.mrzhou.core.tool.utils;

import java.io.IOException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * RSA 加解密工具类
 * @author qiang.zhou
 */
public class RsaUtil {

    /**
     * 生成秘钥对
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return keyPair;
    }

    /**
     * 获取公钥(Base64编码)
     * @param keyPair
     * @return
     */
    public static String getPublicKey(KeyPair keyPair) {
        PublicKey publicKey = keyPair.getPublic();
        byte[] bytes = publicKey.getEncoded();
        return byte2Base64(bytes);
    }

    /**
     * 获取私钥(Base64编码)
     * @param keyPair
     * @return
     */
    public static String getPrivateKey(KeyPair keyPair) {
        PrivateKey privateKey = keyPair.getPrivate();
        byte[] bytes = privateKey.getEncoded();
        return byte2Base64(bytes);
    }

    /**
     * 将Base64编码后的公钥转换成PublicKey对象
     * @param pubStr
     * @return
     * @throws Exception
     */
    public static PublicKey string2PublicKey(String pubStr) throws Exception {
        byte[] keyBytes = base642Byte(pubStr);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 将Base64编码后的私钥转换成PrivateKey对象
     * @param priStr
     * @return
     * @throws Exception
     */
    public static PrivateKey string2PrivateKey(String priStr) throws Exception {
        byte[] keyBytes = base642Byte(priStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    /**
     * 公钥加密
     * @param content
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static byte[] publicEncrypt(byte[] content, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] bytes = cipher.doFinal(content);
        return bytes;
    }

    /**
     * 私钥解密
     * @param content
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] privateDecrypt(byte[] content, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] bytes = cipher.doFinal(content);
        return bytes;
    }

    /**
     * 字节数组转Base64编码
     * @param bytes
     * @return
     */
    public static String byte2Base64(byte[] bytes) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }

    /**
     * Base64编码转字节数组
     * @param base64Key
     * @return
     * @throws IOException
     */
    public static byte[] base642Byte(String base64Key) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(base64Key);
    }


    public static void main(String[] args) {

        String pbk="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCVsMqgquUgUP6XCyUrkq1tI/H0r6bKdIzzi30R/WD2AI9YMaKTLaNMciUoNi1fMGVtXzXaqBHPaJZrW5MrApbxDJ9Arl2WsoQSHHBGP2CMjNdFmmmXkILENlQzrBzndDgSAVCNpGMQOdWMk6MrlsghrQ+7QsUFFrpdRW0rY8vFQIDAQAB";

        String prik="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIJWwyqCq5SBQ/pcLJSuSrW0j8fSvpsp0jPOLfRH9YPYAj1gxopMto0xyJSg2LV8wZW1fNdqoEc9olmtbkysClvEMn0CuXZayhBIccEY/YIyM10WaaZeQgsQ2VDOsHOd0OBIBUI2kYxA51YyToyuWyCGtD7tCxQUWul1FbStjy8VAgMBAAECgYBb6+zAsl9n4LKcgx09zp4KAEnW155tt9TzjFmEiqtwTItn1jSvnOKyOYYIrFepx06P0us00ZIwLBuvu0yq7jpu8oVcbHjxUBpAWejSSH2hXKD7GTbUwbKY4tzdjqzZSwZHuJMW4SK8Rh8X02ZWcmA/dU/GExe6L/AbE8tFFj1WAQJBAMurJA/lgA6QsXW2laZoGyFcySO8ZUBtxUINryH8Y2pCCEhWvomOvyVTVjY5mQCplAwwCDxTq2QAk9MmxR53SaECQQCj1CoUrFEr4V5bZfX7A5dDKUL1qDEvKGzFK6YKq9Jj0FGGWIi/gFhkEo9m20W8gBERLJJ7//s5Kz0V4Q/aOrj1AkEAyTXYuMO5EaqtR2gMzIvJUdqC9IUpWs+Xs7wlK2RXKyD1YdIhB3E5Mjz0zTl2CQt/sdK6MC9RAcj4QgDpeUHMQQJAXfg5NuhsGsZHUBeY0yUJI03MiYmyxIDkeugBcoeBwxzfVjb8IRPmH2iB9pZ5VpkCsR4m25dFq1IA1MbmR9987QJAGljKn+jLjO2BCJDVsmp5qQymAy6UD28+ArKyUNI8oipwQWdEDeLqUn1EymtstTqxUdOwU6Zork6GGyzvZTlTdA==";


        try {
            //===============生成公钥和私钥，公钥传给客户端，私钥服务端保留==================
            //生成RSA公钥和私钥，并Base64编码
//            KeyPair keyPair = RSAUtil.getKeyPair();
//            String publicKeyStr = RSAUtil.getPublicKey(keyPair);
//            String privateKeyStr = RSAUtil.getPrivateKey(keyPair);
//            System.out.println("RSA公钥Base64编码:" + publicKeyStr);
//            System.out.println("RSA私钥Base64编码:" + privateKeyStr);

            //=================客户端=================
            //hello, i am infi, good night!加密
            String message = "你好啊!";
            //将Base64编码后的公钥转换成PublicKey对象
            PublicKey publicKey = RsaUtil.string2PublicKey(pbk);
            //用公钥加密
            byte[] publicEncrypt = RsaUtil.publicEncrypt(message.getBytes(), publicKey);
            //加密后的内容Base64编码
            String pbkStr=new String(publicEncrypt);
            System.out.println("公钥加密结果：" + pbkStr);
//            String byte2Base64 = RSAUtil.byte2Base64(publicEncrypt);
//            System.out.println("公钥加密并Base64编码的结果：" + byte2Base64);


            //##############    网络上传输的内容有Base64编码后的公钥 和 Base64编码后的公钥加密的内容     #################
            PrivateKey privateKey = RsaUtil.string2PrivateKey(prik);
            //用私钥解密
            byte[] privateDecrypt = RsaUtil.privateDecrypt(publicEncrypt, privateKey);
            System.out.println("解密后的明文: " + new String(privateDecrypt));
//            //===================服务端================
//            //将Base64编码后的私钥转换成PrivateKey对象
//            PrivateKey privateKey = RSAUtil.string2PrivateKey(privateKeyStr);
//            //加密后的内容Base64解码
//            byte[] base642Byte = RSAUtil.base642Byte(byte2Base64);
//            //用私钥解密
//            byte[] privateDecrypt = RSAUtil.privateDecrypt(base642Byte, privateKey);
//            //解密后的明文
//            System.out.println("解密后的明文: " + new String(privateDecrypt));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
